package com.hong.pro.utils;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.hong.pro.annotation.Column;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Objects;

/**
 * @Description:
 * @Author Hong Qiang
 * @Date 2023/11/20 16:09
 * @Version 1.0
 */
public class SqlUtil {

    public static void main(String[] args) {
//        System.out.println(            StrUtil.replaceLast("a,cd,cca,ss,c",",",""));
    }


    /**
     * 生成建表Sql
     * @param c
     * @return
     */
    private static String generateTableSql(Class c){
        StringBuilder columnSql = new StringBuilder();//字段建表
        StringBuilder commentSql = new StringBuilder();//注释
        String tableName = c.getSimpleName().toUpperCase();//表名
        Column column = (Column) c.getAnnotation(Column.class);
        if (Objects.nonNull(column)){
            tableName = column.value();
        }
        columnSql.append("CREATE TABLE ").append(tableName).append("\r\n")
                .append("(").append("\r\n");
        commentSql.append("comment on table ").append(tableName).append("\r\n")
                .append("    is '").append(StrUtil.blankToDefault(column.comment(),"表名注释")).append("';").append("\r\n");
        Field[] fields = ReflectUtil.getFields(c);
        //循环遍历每个加了注解的字段
        String finalTableName = tableName;
        Arrays.stream(fields).filter(field->Objects.nonNull(field.getAnnotation(Column.class))).forEach(field -> {
            Column col = field.getAnnotation(Column.class);
            String columnName = StrUtil.blankToDefault(col.value().toUpperCase(),StrUtil.toUnderlineCase(field.getName()).toUpperCase());
            Class<?> type = field.getType();
            String columnType = "";
            if (Arrays.asList("java.lang.Integer","int").contains(type.getTypeName())){
                columnType = "NUMBER(" + StrUtil.blankToDefault(col.length(),"1") + "),";
            }else if ("java.lang.String".equals(type.getTypeName())){
                columnType = "VARCHAR2(" + StrUtil.blankToDefault(col.length(),"20") + "),";
            }else if ("java.math.BigDecimal".equals(type.getTypeName())){
                columnType = "NUMBER(" + StrUtil.blankToDefault(col.length(),"12,2") + "),";
            }else {
                columnType = col.colType()+"(" + col.length() + "),";
            }
            columnSql.append("    ").append(columnName).append("    ").append(columnType).append("\r\n");
            commentSql.append("comment on column ").append(finalTableName).append(".").append(columnName).append("\r\n")
                    .append("    is '").append(StrUtil.blankToDefault(column.comment(),"字段注释")).append("';").append("\r\n");
        });

        columnSql.append(");").append("\r\n").append(commentSql);
        return StrUtil.replaceLast(columnSql.toString(),",","");
    }
}
